#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    bool bp[501][501], c = true;
    int numEnclaves(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size(), ret = 0;
        for (int i = 0; i < n; i++)
            if (grid[i][0] == 1 && bp[i][0] == false)
                bfs(grid, i, 0, 0);
        for (int i = 0; i < n; i++)
            if (grid[i][m - 1] == 1 && bp[i][m - 1] == false)
                bfs(grid, i, m - 1, 0);
        for (int j = 0; j < m; j++)
            if (grid[0][j] == 1 && bp[0][j] == false)
                bfs(grid, 0, j, 0);
        for (int j = 0; j < m; j++)
            if (grid[n - 1][j] == 1 && bp[n - 1][j] == false)
                bfs(grid, n - 1, j, 0);
        for (int i = 1; i < n - 1; i++)
            for (int j = 1; j < m - 1; j++)
                if (grid[i][j] == 1)
                    ret++;
        return ret;
    }
    void bfs(vector<vector<int>>& board, int i, int j, int ch) {
        queue<pair<int, int>> q;
        q.push({ i, j });
        bp[i][j] = true;
        board[i][j] = ch;
        while (q.size()) {
            auto [x, y] = q.front();
            q.pop();
            for (int k = 0; k < 4; k++) {
                int a = x + dx[k], b = y + dy[k];
                if (a >= 0 && a < board.size() && b >= 0 &&
                    b < board[a].size() && board[a][b] == 1 &&
                    bp[a][b] == false)
                    bp[a][b] = true, board[a][b] = ch, q.push({ a, b });
            }
        }
    }
};